/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.jasoet.provider;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

/**
 *
 * @author Deny Prasetyo
 */
public class SessionFactoryProvider {

    private SessionFactory sessionFactory;
    private static SessionFactoryProvider provider;

    private SessionFactoryProvider() throws ExceptionInInitializerError{
        try {
            this.sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactoryProvider getInstance() throws ExceptionInInitializerError{
        SessionFactoryProvider tempProvider = null;
        if (provider == null) {
            provider = new SessionFactoryProvider();
            tempProvider = provider;
        } else if (provider.getSessionFactory() == null) {
            provider = new SessionFactoryProvider();
            tempProvider = provider;
        } else if (provider.getSessionFactory().isClosed()) {
            provider = new SessionFactoryProvider();
            tempProvider = provider;
        } else {
            tempProvider = provider;
        }

        return tempProvider;
    }

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
}
